package com.h3bpm.web.instance.applicationAgencyNo;

import OThinker.Common.Organization.Models.User;
import OThinker.H3.Entity.DataModel.BizObject;
import OThinker.H3.Entity.Instance.Data.InstanceData;
import com.alibaba.fastjson.JSONObject;
import com.h3bpm.base.util.AppUtility;
import com.h3bpm.handler.JSONUtils;
import com.h3bpm.web.config.UrlConfig;
import com.h3bpm.web.instance.applicationAgencyNo.dao.AgencyNoDao;
import com.h3bpm.web.protalHanding.OrcaleHelper;
import com.h3bpm.web.protalHanding.ThreadPost;
import com.h3bpm.web.reback.controller.WritebackController;
import com.h3bpm.web.reback.service.RebackService;
import com.h3bpm.web.util.DateUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author villwang
 * @date 2020/07/30
 **/
@RestController
@RequestMapping("/Portal/Instances")
public class ApplicationAgencyNoController {

    @Autowired
    private AgencyNoDao agencyNoDao;

    @Autowired
    private RebackService rebackService;

    private static final Logger logger = LoggerFactory.getLogger(ApplicationAgencyNoController.class);

    /**
     * 获取报告号并回写
     * @param instanceId
     * @param workflowCode
     * @return
     */
    @RequestMapping("/getAgencyNoWriteBack")
    public JSONObject getReportNos(String instanceId, String workflowCode){
        synchronized (ApplicationAgencyNoController.class){
            JSONObject result = new JSONObject();
            String reportNo = getReportNo();
            boolean flag = false;
            logger.info("获取招标代理号————————————————-reportNo:"+reportNo);
            if(StringUtils.isNotBlank(reportNo)){
                flag = addAgencyNo(instanceId, reportNo);
            }
            logger.info("招标代理号回写EC————————————————-flag:"+flag);
            if(flag){
                //招标代理号回写OA(流程数据回写OA)
                flag = rebackService.applicationAgencyNo(instanceId, workflowCode, reportNo);
            }
            logger.info("招标代理号回写OA————————————————-flag:"+flag);
            if(flag){
                result.put("state", "200");
                result.put("msg", "success");
            }
            return result;
        }
    }

    public String getReportNo(){
//        JSONObject result = new JSONObject();
        String data = null;
        try {
            String biddingAgencyNo="";
            String newBiddingAgencyNo="";
            Integer no=0;
            String newBiddingAgencyNoYear="";
            biddingAgencyNo = agencyNoDao.getMaxAgencyNo();
            if(StringUtils.isNotBlank(biddingAgencyNo)){
                if(biddingAgencyNo.length()>4){
                    newBiddingAgencyNo=biddingAgencyNo.substring(biddingAgencyNo.length()-4);
                }
                if(biddingAgencyNo.length()>10){
                    newBiddingAgencyNoYear=biddingAgencyNo.substring(6,10);
                }
            }
            if(StringUtils.isNotBlank(newBiddingAgencyNo)){
                no=Integer.parseInt(newBiddingAgencyNo);

            }
            if(StringUtils.isNotBlank(newBiddingAgencyNoYear)&&!newBiddingAgencyNoYear.equals(String.valueOf(DateUtil.getYear()))){
                data = "H0701-"+ DateUtil.getYear()+"-"+"0001";
            }else{
                no=no+1;
                String str = "000000" + no.toString();
                str = str.substring(str.length() - 4);
                str = "H0701-"+ DateUtil.getYear()+"-"+str;
                data = str;
            }
//            logger.info("获取招标代理号—————————str———————-"+result.get("data"));
//            result.put("state", "200");
//            result.put("msg", "success");
//            return data;
        } catch (Exception e) {
            e.printStackTrace();

        }
        return data;
    }

    //招标代理号回写EC
    public boolean addAgencyNo(String instanceId, String reportNo){
        boolean flag = true;
        InstanceData instanceData = null;
        try {
            instanceData = new InstanceData(AppUtility.getEngine(), instanceId, User.AdministratorID);
            BizObject bizObject = instanceData.getBizObject();
            HashMap<String, Object> body = new HashMap<>();
            body.put("guid", bizObject.GetValue("guid"));
            body.put("businessId", bizObject.GetValue("businessId"));
            body.put("agencyNo", StringUtils.isNotBlank(reportNo)?reportNo:(String)bizObject.GetValue("biddingAgencyNo"));
            body.put("sectionName", bizObject.GetValue("noName"));
            body.put("agencyName", bizObject.GetValue("tendererName"));
            body.put("agencyType", bizObject.GetValue("tenderMethod"));
            body.put("agencyTypeOne", bizObject.GetValue("tenderCategory1"));
            body.put("agencyTypeTwo", bizObject.GetValue("tenderCategory2"));
            body.put("supervisionDept", bizObject.GetValue("regulators"));
            body.put("issueMedia", bizObject.GetValue("publishingMedia"));
            body.put("otherMedia", bizObject.GetValue("otherMedia"));
            body.put("budgetNo", bizObject.GetValue("governmentBudgetNo"));
            body.put("applicationNo", bizObject.GetValue("constructionApplicationNo"));
            body.put("otherNo", bizObject.GetValue("blocks"));
            body.put("referenceNo", bizObject.GetValue("acceptanceNumber"));
            body.put("createBy", bizObject.GetValue("userName"));
            body.put("createTime", bizObject.GetValue("dateFilling"));
            String url = UrlConfig.BusinessUrl+"/prod-api/workflow/addAgencyNoNew";
            String json = JSONUtils.toJson(body);
            Map<String, Object> result = ThreadPost.postRequestResult(url,json,null);
            if(result==null||result.size()==0){
                logger.debug("返回值为空—————————————");
            }else {
                int res= (Integer) result.get("code");
                if(res==200){
                    flag = true;
                    logger.debug("更新实例结果====================success");
                }else {
                    logger.debug("更新实例结果====================失败");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    @RequestMapping("/getHistoryAgencyNo")
    public JSONObject getHistoryAgencyNo(String projectCode, String businessStatus){
        JSONObject result = new JSONObject();
        result.put("state", "200");
        result.put("msg", "success");
        result.put("data", agencyNoDao.getHistoryAgencyNo(projectCode, businessStatus));
        return result;
    }
}
